﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data;
using Logistics.Configuration;
using DataUpload;
using Logistics.DataManage.Local;
using Logistics.DataManage.Server;
using MapgisEbp.QuickDataBase;
using MapgisEbp.QuickDataBase.Common;
using Logistics.Utils;

namespace Logistics.DataManage
{
    public class DataDownloader : AbstractWorker
    {
        /// <summary>
        /// 是否下载客户信息
        /// </summary>
        public bool DownloadCustomers {get;set;}
        /// <summary>
        /// 开始工作
        /// </summary>
        public override void DoWork()
        {
            try
            {
                LogUtils.WriteLog("开始准备下载数据--DataDownloader");
                DownLoadDataFromSever();
                LogUtils.WriteLog("数据下载完毕--DataDownloader");
            }
            catch(Exception ex)
            {
                LogUtils.WriteLog(ex.ToString());
                FailState state = new FailState() {FailedMsg=ex.ToString() };
                this.RaiseFail(state);
            }
        }
        /// <summary>
        /// 取消工作
        /// </summary>
        public override void Cancle()
        {

        }

        #region 从服务器下载数据，同步到本地数据库
        private void DownLoadDataFromSever()
        {
            String[] TableNames = GlobalObjects.GSetting.DownloadTables;
            String msg = "下载数据文件分析成功，开始下载数据！请稍等……";
            LogUtils.WriteDebug(msg);
            RaiseUpdate(new WorkState() { Process = 0, ProcessMsg = msg });
            int count = TableNames.Length;
            int i = 0;
            foreach (var tableName in TableNames)
            {
                int percent = Convert.ToInt32(Math.Floor((Convert.ToDouble(i + 1) / count) * 100));
                msg = String.Format("正在更新表{0},请稍等……", tableName);
                LogUtils.WriteDebug(msg);
                RaiseUpdate(new WorkState() { Process = percent, ProcessMsg = msg });
                DownLoadDataFromSever(tableName);
                i++;
            }
            this.RaiseComplete();
        }

        private void DownLoadDataFromSever(String tableName)
        {
            if (String.Compare(tableName,"Customs",true)==0)
            {
                if (DownloadCustomers)
                {
                    CustomerDownloader cusDownloader = new CustomerDownloader();
                    cusDownloader.Update += (state) => { this.RaiseUpdate(state); };
                    cusDownloader.Fail += (state) => { this.RaiseFail(state); };
                    cusDownloader.DownloadCustomersAsyn();
                }
                return;
            }
            DataSet dsRetrun = RemoteDateServiceFactory.DateService.GetSynchronous("", "*", tableName);//下载数据
            if (dsRetrun != null && dsRetrun.Tables[0].Rows.Count != 0)
            {
                LogUtils.WriteDebug(String.Format("从服务器表{0}下载到{1}条数据", tableName, dsRetrun.Tables[0].Rows.Count));
                InsertClientData(tableName, dsRetrun);
            }
        }

        /// <summary>
        /// 将服务器数据写入本地数据库中
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="dsRetrun"></param>
        private static bool InsertClientData(string tableName, DataSet dsRetrun)
        {
            DataTable TemlateDT = LocalDb.TableTemplates[tableName];
            if (TemlateDT == null) return false;
            IList<String> colNames = MappingLocalColumns(TemlateDT, dsRetrun.Tables[0]);
            using (DbTransactionScope scope = new DbTransactionScope(LocalDb.Handler))
            {
                try
                {
                    //先删除数据
                    LocalDb.Handler.ExecuteNonQuery("delete from  " + tableName);
                    DataTable dt = dsRetrun.Tables[0];
                    for (int j = 0; j < dsRetrun.Tables[0].Rows.Count; j++)
                    {
                        IList<object> parameters = null;
                        String sql = DataConvert.GenerateInsertSQLFromDataRow(dt.Rows[j], tableName, colNames.ToArray(), out parameters);
                        ParameterizedSQL PSQL = LocalDb.Handler.DbAdapter.AdaptSQLAnonymousParams(sql, parameters.ToArray());
                        int result = LocalDb.Handler.ExecuteNonQuery(PSQL.SQL, PSQL.Parameters);
                    }
                    scope.Complete();
                    return true;
                }
                catch
                {
                    scope.Dispose();
                    return false;
                }
            }
        }
        /// <summary>
        /// 获取相匹配的列名称,防止远程数据表比本地数据表字段多
        /// </summary>
        /// <param name="TemplateDT"></param>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static IList<String> MappingLocalColumns(DataTable TemplateDT, DataTable dataTable)
        {
            IList<String> list = new List<String>();
            foreach (DataColumn col in TemplateDT.Columns)
            {
                String colName = col.ColumnName;
                foreach (DataColumn colx in dataTable.Columns)
                {
                    String targetColName = colx.ColumnName;
                    if (String.Compare(colName, targetColName, true) == 0)
                        list.Add(targetColName);//这里处理大小写问题
                }
            }
            return list;
        }
        #endregion
    }
}
